import json
import requests

APIPassword = "Bearer QdoSJjUpKEotpPRZefVO:aaJeSlTMCGWZIBKQhkTc"
url = "https://spark-api-open.xf-yun.com/v2/chat/completions"

# 请求模型，并将结果输出
def get_answer(message):
    #初始化请求体
    headers = {
        'Authorization':APIPassword,
        'content-type': "application/json"
    }
    body = {
        "model": "x1",
        "user": "user_id",
        "messages": message,
        # 下面是可选参数
        "stream": True
    }
    full_response = ""  # 存储返回结果

    try:
        response = requests.post(url=url,json= body,headers= headers,stream= True)
        if response.status_code != 200:     # 检查响应状态码
            return f"API请求失败: {response.status_code}" 
        for chunks in response.iter_lines():
            if (chunks and b'[DONE]' not in chunks):    # 检查chunk是否为空且不包含[DONE]，在星火模型中，[DONE] 是一个用于标识流式响应结束的特殊标记。
                try:
                    if len(chunks) > 6:     # 检查chunk长度是否足够
                        data_org = chunks[6:]
                        try:    # 尝试解析JSON  
                            chunk = json.loads(data_org)
                            if 'choices' in chunk and len(chunk['choices']) > 0 and 'delta' in chunk['choices'][0]: # 检查必要字段是否存在
                                text = chunk['choices'][0]['delta']
                                if ('content' in text and '' != text['content']):   # 只获取最终的文本内容
                                    content = text["content"]
                                    print(content, end="")
                                    full_response += content
                        except json.JSONDecodeError:
                            pass
                except Exception:
                    pass
        return full_response
    except requests.exceptions.RequestException as e:
        print(f"请求异常: {str(e)}")
        return f"请求异常: {str(e)}"
    except Exception as e:
        print(f"发生未知错误: {str(e)}")
        return f"发生未知错误: {str(e)}"


# 管理对话历史，按序编为列表
def getText(text,role, content):
    jsoncon = {}
    jsoncon["role"] = role
    jsoncon["content"] = content
    text.append(jsoncon)
    return text

# 获取对话中的所有角色的content长度
def getlength(text):
    length = 0
    for content in text:
        temp = content["content"]
        leng = len(temp)
        length += leng
    return length

# 判断长度是否超长，当前限制8K tokens
def checklen(text):
    while (getlength(text) > 11000):
        del text[0]
    return text


#主程序入口
if __name__ =='__main__':
    #对话历史存储列表
    chatHistory = []
    #循环对话轮次
    while (1):
        # 等待控制台输入
        Input = input("\n" + "我:")
        question = checklen(getText(chatHistory,"user", Input))
        # 开始输出模型内容
        print("星火:", end="")
        getText(chatHistory,"assistant", get_answer(question))


